<script type="text/javascript">
	
	panel.workspace.autoload = function() {
		
		var overview = {};
		
		/**
		 * Overview 
		**/
		overview.state    = {};
		overview.observer = new Ext.util.Observable();
				
		overview.observer.addEvents({
			
			"init": true
			
		});
		
		overview.observer.on("init", function() {
		
			overview.locker = new Ext.ux.locker;
			overview.locker.setElement( Ext.get(overview.viewport.getEl()) );
			
		});
		
		overview.observer.on("init", function() { overview.list.init(); });
		
		overview.list = panel.widgets.list({
			
			hierarchy: true,
			
			store: {
				
				fields: [
					{ name: "uid",           type: "string" },
					{ name: "eid",           type: "int"    },
					{ name: "etype",         type: "string" },
					{ name: "title",         type: "string" },
					{ name: "parent",        type: "string" },
					{ name: "is_lead",       type: "bool"   },
					{ name: "ip",            type: "string" },
					{ name: "vendor_id",     type: "int"    },
					{ name: "vendor_title",  type: "string" }
				]
				
				
			},
			
			selection: {
				
				useSelection: false,
				hooks: {
					
					check_model_column_config: {
					
						hdCheckbox: false,
						onChange: function(col, store, record, state) {
							
							switch( record.data.etype ) {
							
							case "VENDOR":
								
								col.checkRecords(
									
									store.queryBy( function(f) { 
									
										return ( f.data.parent == record.data.uid );
								
									}),
									
									state
									
								);
								
								break;
								
							case "DEVICE":
							
								if( !state ) {
							
									col.checkRecords( store.query("uid", record.data.parent), false );
									
								}
								
								break;
								
							}
							
						}
						
					}
					
				}
				
			},
			
			search: {
				
				width: 400,
				minChars: 2,
				
				toolbarContainer: function() { return overview.viewport; },
				
				checkIndexes: [
				
					"title", "ip", "vendor"
				
				]
				
			},
			
			filters: {
			
				fields: [
				
					{ dataIndex: "title",      type: "string"  }
				
				]
				
			},
			
			grid: {
				
				autoExpandColumn : "title",
				master_column_id: "title",
				margins: "0 0 0 0",
				border: false,
				
				columns: [
				
					{
						
						header: "Name",
						id: "title",
						dataIndex: "title",
						
						renderer: function( v, cell, record ) {
							
							switch( record.data.etype ) {
							
							case "VENDOR":
								
								cell.css += " s_bold ";
								
								break;
								
							}
							
							return v;
							
						}
						
					},
					
					{
						header: "Vendor",
						dataIndex: "vendor_title",
						width: 100
					},
					
					{
						header: "IP",
						dataIndex: "ip",
						width: 100
					}		
					
				],
				
				viewConfig: {
					
					getRowClass: function(record) {
						
						switch( record.data.etype ) {
							
						case "VENDOR":
							
							return " g_ext_group ";
							
							break;
							
						}
						
					}
					
				}
				
			}
			
		});
		
		overview.reload = function() {
			
			panel.ajax({
				
				_p:  "devices_overview",
				_pa: "get_overview_data",
				_rt: "text/json",
				
				onRequest: function() {
					
					overview.locker.lock("Loading data...");
					
				},
				
				onFailure: function() {
					
					overview.locker.unlock();
					return false;
					
				},
				
				onComplete: function(r) {

					overview.list.loadData(r, { expandAll: true });
					overview.observer.fireEvent("reload");
					overview.locker.unlock();
					
				}
				
			}).request();
			
		};
		
		overview.observer.on("init", function() { overview.reload(); });
		
		/**
		 * Actions
		 */
		overview.actions = {};
		
		overview.actions.run_command = new Ext.Button({
			
			id       : "button_run_command",
			cls      : "x-btn-size-38 w_max x-btn-text-icon",
			iconCls  : "icon_action_run",
			text     : "Run command",
			disabled : true,
			
			handler  : function() {
				
				try {

				var devices = ( function() { 
				
					var items = overview.list.selection.getSelections();
					
					items.each( function(item, key) {
						
						if( item.data.etype != "DEVICE" ) {
							delete items[key]; }
						
					} );
					
					return $A(items).clean();
					
				}());
				
				if( !devices.length ) {
					throw "No selected devices"; }
					
				var vendor      = null;
				
				devices.each( function(dev) {

					if( vendor == null ) {
						
						vendor = dev.data.vendor_id;
						
					} else if( vendor != dev.data.vendor_id ) {
						
						throw "Commands cannot be executed on devices from different vendors.";
						
					}
					
				});
				
				var f = {% include file='devices_overview/overview.form.run_command.js' %};
				
				f({
					
					devices: (function() {  
					
						var r = [];
												
						devices.each( function(dev) {
							
							r.push(dev.data.eid); 
							
						}); 
					
						return r;
					
					}()),
					
					vendor_id: vendor,
					
					callback: function(state) {
						
						
						
					}
					
				});
				
				} catch( e ) {
					
					if( typeof(e) != "string" ) {
						throw e; }
					
					panel.ui.alert.alert(e);
					return;
					
				}
				
				
			}
						
		});
		
		/**
		 * Sidebar 
		**/
		overview.sidebar = panel.widgets.sidebar({
			
			split: true,
			region: "west",
			
			items: [
				
				overview.actions.run_command
				
			],
			
			getInfo: function() {
				
				var r = [];
				
				r.push("<h1>Overview:</h1>");

				if( overview.list.selection.hasSelection() ) {
					
					var status = {
					};
					
					if( overview.list.selection.getSelections().length == 1 ) {
						
						var s = overview.list.selection.getSelections()[0];

						switch( s.data.etype ) {
						
						case "DEVICE":
						
							status.text  = s.data.name;
							status.icon  = "icon_e_device";
							status.color = "";
							status.description = "";
						
							break; 
						
						}	// switch
						
					} else {
						
						status.length = (function() {
							
							var i = 0;
							
							overview.list.selection.getSelections().each( function(s) {
								
								if( s.data.etype == "DEVICE" ) {
									i++; }
								
							} );
							
							return i;
							
						}());
						
						status.text = "<b>" + status.length + "</b> devices."; 
						status.icon = "icon_e_selection_32";
						status.description = "Actions will be applied on chosen items.";
						status.color = "";
						
					}	// if
					
					r.push(
						"<div class='hr'></div>",
						"<div class='a_center'><span class='icon_frame icon_32 ", status.icon, "'></span></div>",
						"<div class='a_center'>You have selected:</div>", 
						"<h1 class='", status.color, "'>", status.text, "</h1>",
						"<div class='a_center s_small'>", status.description,"</div>"						
					);
					
				} else {
					
					r.push(
						"<div class='hr'></div>",
						"<div class='a_center bg_info'>To unlock action buttons, please choose a item.</div>"
					);
					
				}	// if
				
				return r.join("");
			
			},
			
			processItemsStatus: function(items) {
				
				if( overview.list.selection.hasSelection() ) {
					
					overview.actions.run_command.enable();
					
				} else {
					
					overview.actions.run_command.disable();
					
				}	// if
				
			},
			
			listeners: {
				
				init: function(me) {
					
					var _fe = function() { me.refresh(); }
					
					overview.list.selection.observer.on("selection", _fe);
					
				}
				
			}
			
		});
		
		/**
		 * Viewport: 
		**/
		
		overview.viewport = new Ext.Panel({
			
			title      : "Devices",
			renderTo   : panel.viewport.content.getContentEl(),
			height     : panel.viewport.content.getInnerHeight() - 5,
			
			plain  : false,
			
			layout: "border",
			
			tools: [
				panel.widgets.chunks.panel.tools
				.refresh({ handler: function() { overview.reload() } })
				.tool
			],
			
			tbar: new Ext.Toolbar({
				
				height: 27,
				items: [ "->" ]
				
			}),
			
			items: [
				overview.list.panel,
				overview.sidebar.getPanel()
			],
			
			listeners: {
				
				// Reference required
				beforerender: function(me) {

					overview.viewport = me;
					
				},
				
				afterlayout: function() {
					
					/**
					 * 1. Do init.
					 * 2. Avoid reinitialization if defined 
					**/

					if( !overview.state.init ) {
						
						overview.state.init = true;
						overview.observer.fireEvent("init");
						
					}	// if
					
				}
				
			}
			
		});
		
	}
	
</script>